package com.ztesoft.web.index.controller;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.ztesoft.framework.exception.BaseAppException;
import com.ztesoft.framework.log.ZTEsoftLogManager;
import com.ztesoft.framework.util.DateUtils;
import com.ztesoft.framework.util.Utils;
import com.ztesoft.iocp.utils.HttpUtils;
import com.ztesoft.web.common.DMSConstant;
import com.ztesoft.web.common.customdb.dao.dto.ApprovaTaskStageDto;
import com.ztesoft.web.common.customdb.dao.dto.ApprovalDto;
import com.ztesoft.web.common.db.arg.SysParamArg;
import com.ztesoft.web.common.db.dao.SysParamDao;
import com.ztesoft.web.common.db.po.SysModulePO;
import com.ztesoft.web.common.db.po.SysParamPO;
import com.ztesoft.web.common.service.ISysModuleService;
import com.ztesoft.web.index.db.po.EchartsDataPO;
import com.ztesoft.web.index.db.po.SpaceDataPO;
import com.ztesoft.web.index.db.po.WarningInfoPO;
import com.ztesoft.web.index.service.IIndexService;
import com.ztesoft.web.taskgenerator.service.IDmTaskService;

@Controller
@RequestMapping("/index")
public class IndexController {
	private static final ZTEsoftLogManager logger = ZTEsoftLogManager.getLogger(IndexController.class);
	@Autowired
	private ISysModuleService sysModuleService;
	@Autowired
	private IDmTaskService taskService;
	@Autowired
	private IIndexService indexService;
	@Autowired
	private SysParamDao sysParamDao;

	private String toCleanUnit = "G";

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

	/**
	 * 访问前台界面
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("index")
    @ResponseBody
    public ModelAndView index(Model model) {
    	ModelAndView view = new ModelAndView("index");
    	view.addObject("moduleMainView","home/views/HomeView");
    	return view;
    }
	
	/**
	 * 查询所属系统的下拉框
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("searchSysmodule")
	@ResponseBody
	public List<SysModulePO> searchSysmodule() throws BaseAppException {
		logger.debug("Select module_id,module_name from sys_module where module_level=0");
		List<SysModulePO> list = new ArrayList<SysModulePO>();
		list = sysModuleService.searchSysmodule();
		return list;
	}

	/**
	 * 统计任务数(-1表示该参数无效)
	 * 
	 * @param sourceType
	 *            数据类型
	 * @param state
	 *            任务实例状态
	 * @param offset
	 *            偏移量0,1,3,6,12
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("searchTaskNum")
	@ResponseBody
	public int searchTaskNum(Integer sourceType, Integer nodeId, String state, Integer offset) throws BaseAppException {
		logger.debug("Select count(*) from dm_task where SOURCE_TYPE={0} ", sourceType);
		Date date = null;
		if (!Utils.isEmpty(offset) && offset != -1) {
			date = DateUtils.offersetMonth(DateUtils.getNowDate(), -offset);
		}
		return indexService.searchTaskNum(sourceType, nodeId, state, date);
	}

	/**
	 * 获取待审核的数据数
	 * 
	 * @param sourceType
	 * @param nodeId
	 * @return
	 */
	@RequestMapping("getIsCheckNum")
	@ResponseBody
	public int getIsCheckNum(Integer sourceType, Integer nodeId) {
		return indexService.getIsCheckNum(sourceType, nodeId);
	}

	/**
	 * 查询告警信息
	 * 
	 * @return
	 */
	@RequestMapping("queryWarnningInfo")
	@ResponseBody
	public List<WarningInfoPO> queryWarnningInfo() {
		logger.debug("/r/n|查找系统参数|");
		String queryUrl = "";
		String subSysIp = "";
		String subSysPort = "";
		SysParamArg sysParamArg = new SysParamArg();
		SysParamArg.SysParamCriteria sysParamCriteria = sysParamArg.createCriteria();
		sysParamCriteria.andStateEqualTo(DMSConstant.Status.SUCCESS.toString());
		List<SysParamPO> syspParamList = sysParamDao.selectByArg(sysParamArg);
		for (SysParamPO sysParamPO : syspParamList) {
			if ("query.do".equals(sysParamPO.getParamName())) {
				queryUrl = sysParamPO.getParamValue();
			} else if ("subSysIp".equals(sysParamPO.getParamName())) {
				subSysIp = sysParamPO.getParamValue();
			} else if ("subSysPort".equals(sysParamPO.getParamName())) {
				subSysPort = sysParamPO.getParamValue();
			}
		}
		List<WarningInfoPO> list = new ArrayList<WarningInfoPO>();
		// 从IOCP获取数据
		// http://10.45.45.170:8080/IOCP/warning/warninginfo/queryRecordByPage.do?_dc=1441951677294&limit=20&page=1&start=0
		// http://localhost:18080/IOCP/warning/warninginfo/query.do?subSysIp=localhost&subSysPort=28080&warningType=10A(默认按时间倒序)
		try {
			String response = HttpUtils.getDataByUrl(queryUrl + "?subSysIp=" + subSysIp + "&subSysPort=" + subSysPort
					+ "&warningType=10A");
			// response =
			// "[{'warningId':100,'warningName':'CPU-USED1000','warningLevel':'urgent','subSysId':12,'subSysName':null,'warningState':'10A','warningReason':'主机 127.0.0.0 CPU使用率为82.0%，达到系统设置的阀值80.0%，需要暂停任务','warningCode':'12100','warningType':'10A','warningDesc':'主机 127.0.0.0 CPU使用率为82.0%，达到系统设置的阀值80.0%，需要暂停任务','createdTime':'2015-09-11 11:30:18','recoverTime':null},{'warningId':101,'warningName':'MEM-USED1000','warningLevel':'urgent','subSysId':12,'subSysName':null,'warningState':'10A','warningReason':'主机 127.0.0.0 内存使用率为82.0%，达到系统设置的阀值80.0%，需要暂停任务','warningCode':'12101','warningType':'10A','warningDesc':'主机 127.0.0.0 内存使用率为82.0%，达到系统设置的阀值80.0%，需要暂停任务','createdTime':'2015-09-11 11:30:18','recoverTime':null}]";
			list = JSONObject.parseArray(response, WarningInfoPO.class);
		} catch (Exception e) {
			logger.error("|获取告警信息失败|", e);
		}
		return list;
	}

	/**
	 * 统计当前已扫描数据结果大小和已清理数据大小
	 * 
	 * @param sourceType
	 *            数据类型
	 * @param nodeId
	 *            所属系统
	 * @return
	 * @throws BaseAppException
	 */
	@RequestMapping("queryList4Circular")
	@ResponseBody
	public Map<String, Object> queryList4Circular(int sourceType, int nodeId) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			List<String> legendData = new ArrayList<String>();
			List<EchartsDataPO> seriesData = new ArrayList<EchartsDataPO>();
			Date date = DateUtils.offersetMonth(DateUtils.getNowDate(), -1);
			String createDate = sdf.format(date);
			BigDecimal checkSize_original = indexService.getCheckDataSize(sourceType, nodeId, createDate, -1);
			BigDecimal cleanSize_original = indexService.getCleanUpData(sourceType, nodeId);
			BigDecimal checkSize = BigDecimal.ZERO;
			BigDecimal cleanSize = BigDecimal.ZERO;
			if (checkSize_original == null) {
				checkSize_original = BigDecimal.ZERO;
				map.put("success", false);
			} else {
				checkSize = checkSize_original.divide(BigDecimal.valueOf(1024)).divide(BigDecimal.valueOf(1024))
						.setScale(2, RoundingMode.HALF_UP);
				if (cleanSize_original == null) {
					cleanSize_original = BigDecimal.ZERO;
				} else {
					cleanSize = cleanSize_original.divide(BigDecimal.valueOf(1024)).divide(BigDecimal.valueOf(1024))
							.setScale(2, RoundingMode.HALF_UP);
				}
				if (checkSize.compareTo(BigDecimal.ONE) == -1 || cleanSize.compareTo(BigDecimal.ONE) == -1) {// 小于1G
					checkSize = checkSize_original.divide(BigDecimal.valueOf(1024)).setScale(2, RoundingMode.HALF_UP);
					cleanSize = cleanSize_original.divide(BigDecimal.valueOf(1024)).setScale(2, RoundingMode.HALF_UP);
					toCleanUnit = "M";
				}
				BigDecimal toDoSize = checkSize.subtract(cleanSize);
				BigDecimal p1 = BigDecimal.valueOf(toDoSize.floatValue() * 100 / (checkSize.floatValue())).setScale(2,
						RoundingMode.HALF_UP);
				BigDecimal p2 = BigDecimal.valueOf(cleanSize.floatValue() * 100 / (checkSize.floatValue())).setScale(2,
						RoundingMode.HALF_UP);
				legendData.add("未清理量:" + toDoSize + toCleanUnit + "(" + p1 + "%)");
				legendData.add("已清理量:" + cleanSize + toCleanUnit + "(" + p2 + "%)");
				EchartsDataPO toDoData = new EchartsDataPO();
				toDoData.setName("未清理量:" + toDoSize + toCleanUnit + "(" + p1 + "%)");
				toDoData.setValue(toDoSize);
				seriesData.add(toDoData);
				EchartsDataPO cleanUpData = new EchartsDataPO();
				cleanUpData.setName("已清理量:" + cleanSize + toCleanUnit + "(" + p2 + "%)");
				cleanUpData.setValue(cleanSize);
				seriesData.add(cleanUpData);
				map.put("seriesData", seriesData.toArray());
				map.put("legendData", legendData.toArray());
				map.put("checkData", "体检量:" + checkSize + toCleanUnit);
				map.put("success", true);
			}
		} catch (Exception e) {
			logger.error(e.toString());
			map.put("success", false);
		}
		return map;
	}

	/**
	 * 获取空间使用占比
	 * 
	 * @param sourceType
	 *            数据类型
	 * @param nodeId
	 *            所属系统
	 * @return
	 * @throws BaseAppException
	 */
	@RequestMapping("queryList4Pie")
	@ResponseBody
	public Map<String, Object> queryList4Pie(int sourceType, int nodeId, BigDecimal toClean) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			List<String> legendData = new ArrayList<String>();
			List<EchartsDataPO> seriesData = new ArrayList<EchartsDataPO>();
			SpaceDataPO spaceData = indexService.getSpaceSize(sourceType, nodeId);
			BigDecimal totalSize = spaceData.getTotalSize().setScale(2, RoundingMode.HALF_UP);
			BigDecimal usedSize = spaceData.getUsedSize().setScale(2, RoundingMode.HALF_UP);
			BigDecimal toDoSize = totalSize.subtract(usedSize);
			legendData.add("已使用" + usedSize + "G,其中待释放" + toClean + toCleanUnit);
			legendData.add("未使用" + toDoSize + "G");
			EchartsDataPO usedData = new EchartsDataPO();
			usedData.setName("已使用" + usedSize + "G,其中待释放" + toClean + toCleanUnit);
			usedData.setValue(usedSize);
			seriesData.add(usedData);
			EchartsDataPO toDoData = new EchartsDataPO();
			toDoData.setName("未使用" + toDoSize + "G");
			toDoData.setValue(toDoSize);
			seriesData.add(toDoData);
			map.put("success", true);
			map.put("seriesData", seriesData.toArray());
			map.put("legendData", legendData.toArray());
		} catch (Exception e) {
			map.put("success", false);
		}
		toCleanUnit = "G";
		return map;
	}

	/**
	 * 统计已归档数据空间
	 * 
	 * @param sourceType
	 *            数据类型
	 * @param nodeId
	 *            所属系统
	 * @param offset
	 *            偏移量0,1,3,6,12
	 * @return
	 */
	@RequestMapping("getBackUpDataSize")
	@ResponseBody
	public String getBackUpDataSize(int sourceType, int nodeId, int offset) {
		Date date = DateUtils.offersetMonth(DateUtils.getNowDate(), -offset);
		String createDate = sdf.format(date);
		BigDecimal backUpDataSize = indexService.getBackUpDataSize(sourceType, nodeId, createDate, offset);
		if (backUpDataSize == null) {
			return "0M";
		} else {
			backUpDataSize = backUpDataSize.divide(BigDecimal.valueOf(1024)).setScale(2, RoundingMode.HALF_UP);
			if (backUpDataSize.compareTo(new BigDecimal(1024)) <= 0) {
				return backUpDataSize + "M";
			} else {
				backUpDataSize = backUpDataSize.divide(BigDecimal.valueOf(1024)).setScale(2, RoundingMode.HALF_UP);
				return backUpDataSize + "G";
			}
		}
	}

	/**
	 * 统计扫描结果空间
	 * 
	 * @param sourceType
	 *            数据类型
	 * @param nodeId
	 *            所属系统
	 * @param offset
	 *            偏移量0,1,3,6,12
	 * @return
	 */
	@RequestMapping("getCheckDataSize")
	@ResponseBody
	public String getCheckDataSize(int sourceType, int nodeId, int offset) {
		Date date = DateUtils.offersetMonth(DateUtils.getNowDate(), -offset);
		String createDate = sdf.format(date);
		BigDecimal checkDataSize = indexService.getCheckDataSize(sourceType, nodeId, createDate, offset);
		if (checkDataSize == null) {
			return "0M";
		} else {
			checkDataSize = checkDataSize.divide(BigDecimal.valueOf(1024)).setScale(2, RoundingMode.HALF_UP);
			if (checkDataSize.compareTo(new BigDecimal(1024)) <= 0) {
				return checkDataSize + "M";
			} else {
				checkDataSize = checkDataSize.divide(BigDecimal.valueOf(1024)).setScale(2, RoundingMode.HALF_UP);
				return checkDataSize + "G";
			}
		}
	}

	/**
	 * 统计已释放空间
	 * 
	 * @param sourceType
	 *            数据类型
	 * @param nodeId
	 *            所属系统
	 * @param offset
	 *            偏移量0,1,3,6,12
	 * @return
	 */
	@RequestMapping("getResultDataSize")
	@ResponseBody
	public String getResultDataSize(int sourceType, int nodeId, int offset) {
		Date date = DateUtils.offersetMonth(DateUtils.getNowDate(), -offset);
		String createDate = sdf.format(date);
		BigDecimal resultDataSize = indexService.getResultDataSize(sourceType, nodeId, createDate, offset);
		if (resultDataSize == null) {
			return "0M";
		} else {
			resultDataSize = resultDataSize.divide(BigDecimal.valueOf(1024)).setScale(2, RoundingMode.HALF_UP);
			if (resultDataSize.compareTo(new BigDecimal(1024)) <= 0) {
				return resultDataSize + "M";
			} else {
				resultDataSize = resultDataSize.divide(BigDecimal.valueOf(1024)).setScale(2, RoundingMode.HALF_UP);
				return resultDataSize + "G";
			}
		}
	}

	/************************************************************************************************
	 * 审核界面 -- 控制层 -- BEGIN --
	 */

	@RequestMapping("gryApp")
	@ResponseBody
	public List<ApprovalDto> gryApp(ApprovalDto record)
			throws BaseAppException {
		return indexService.gryApp(record);
	}

	@RequestMapping("updateApp")
	@ResponseBody
	public int[] updateApp(ApprovaTaskStageDto taskStage) throws BaseAppException {
		return indexService.updateApp(taskStage);
	}

	@RequestMapping("updateTask")
	@ResponseBody
	public int updateTask(int[] taskIdArr, int isCheck, String desc) throws BaseAppException {
		return indexService.updateTask(taskIdArr, isCheck, desc);
	}
	/**
	 * 审核界面 -- 控制层 -- END --
	 ************************************************************************************************/
}
